package com.chcit.mobile.mvp.receive.adpter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.chcit.mobile.R;
import com.chcit.mobile.app.glide.ImageConfigImpl;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.mvp.receive.Entity.ImageUrl;

import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.utils.ArmsUtils;
import java.util.ArrayList;
import java.util.List;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;

/**
 * @author XUE
 * @since 2019/3/25 11:29
 */
public class ImageSelectGridAdapter extends RecyclerView.Adapter<ImageSelectGridAdapter.ViewHolder> {
    public static final int TYPE_CAMERA = 1;
    public static final int TYPE_PICTURE = 2;
    private LayoutInflater mInflater;
    private List<ImageUrl> mList = new ArrayList<>();
    private int mSelectMax = 1000;
    private AppComponent mAppComponent;
    /**
     * 用于加载图片的管理类, 默认使用 Glide, 使用策略模式, 可替换框架
     */
    private ImageLoader mImageLoader;
    /**
     * 点击添加图片跳转
     */
    private OnAddPicClickListener mOnAddPicClickListener;

    private OnDeletePicClickListener mOnDeletePicClickListener;

    public interface OnAddPicClickListener {
        void onAddPicClick();
    }
    public interface OnDeletePicClickListener {
        void onDeletePicClick(int position,ImageUrl iamge);
    }
    public ImageSelectGridAdapter(Context context, OnAddPicClickListener onAddPicClickListener) {
        mInflater = LayoutInflater.from(context);
        mOnAddPicClickListener = onAddPicClickListener;
    }

    public void setSelectMax(int selectMax) {
        this.mSelectMax = selectMax;
    }

    public void setSelectList(@NonNull List<ImageUrl> list) {
        mList = list;
    }

    public void update(@NonNull List<ImageUrl> list) {
        mList = list;
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView ivSelectPic;
        LinearLayout llDelete;

        public ViewHolder(View view) {
            super(view);
            ivSelectPic = view.findViewById(R.id.iv_select_pic);
            llDelete = view.findViewById(R.id.ll_delete);
            mAppComponent = ArmsUtils.obtainAppComponentFromContext(view.getContext());
            mImageLoader = mAppComponent.imageLoader();

        }
    }

    @Override
    public int getItemCount() {
        if (mList.size() < mSelectMax) {
            return mList.size() + 1;
        } else {
            return mList.size();
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (isShowAddItem(position)) {
            return TYPE_CAMERA;
        } else {
            return TYPE_PICTURE;
        }
    }

    /**
     * 创建ViewHolder
     */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = mInflater.inflate(R.layout.adapter_select_image_grid_item, viewGroup, false);

        return new ViewHolder(view);
    }

    private boolean isShowAddItem(int position) {
        int size = mList.size();
        return position == size;
    }

    /**
     * 设置值
     */
    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
        //少于8张，显示继续添加的图标
        if (getItemViewType(position) == TYPE_CAMERA) {
            viewHolder.ivSelectPic.setImageResource(R.drawable.ic_add_image);
            viewHolder.ivSelectPic.setOnClickListener(v -> mOnAddPicClickListener.onAddPicClick());
            viewHolder.llDelete.setVisibility(View.INVISIBLE);
        } else {
            viewHolder.llDelete.setVisibility(View.VISIBLE);
            viewHolder.llDelete.setOnClickListener(view -> {
                int index = viewHolder.getAdapterPosition();
                if(mOnDeletePicClickListener!=null){
                    mOnDeletePicClickListener.onDeletePicClick(index,mList.get(index));
                }

                // 这里有时会返回-1造成数据下标越界,具体可参考getAdapterPosition()源码，
                // 通过源码分析应该是bindViewHolder()暂未绘制完成导致，知道原因的也可联系我~感谢
//                if (index != RecyclerView.NO_POSITION) {
//                    mList.remove(index);
//                    notifyItemRemoved(index);
//                    notifyItemRangeChanged(index, mList.size());
//                }
            });
            ImageUrl media = mList.get(position);
//            int mimeType = media.getMimeType();

            String path = RetrofitUrlManager.getInstance().getBaseUrl().toString()+HttpMethodContains.Receive.VIEW_ASN_PICTURE+"?index=0&attachmentId="+media.getAttachmentId();
           /* if (media.isCut() && !media.isCompressed()) {
                // 裁剪过
                path = media.getCutPath();
            } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                path = media.getCompressPath();
            } else {
                // 原图
                path = media.getPath();
            }*/

//            mImageLoader.loadImage(viewHolder.itemView.getContext(),
//                    ImageConfigImpl
//                            .builder()
//                            .url(path)
//                            .imageView(viewHolder.ivSelectPic)
//                            .build());
//            RequestOptions options = new RequestOptions()
//                    .centerCrop()
//                    .placeholder(R.color.bg_gray)
//                    .diskCacheStrategy(DiskCacheStrategy.ALL);
//            new GlideUrl(url, new LazyHeaders.Builder().addHeader("Cookie", AppCurrentUser.getInstance().getUserCookie()).build());
//            GlideArms.with(viewHolder.itemView.getContext())
//                    .load(new GlideUrl(path,new LazyHeaders.Builder().addHeader("chcToken", Quick.getToken()).build()))
//                    .apply(options)
//                    .into(viewHolder.ivSelectPic);

            //itemView 的 Context 就是 Activity, Glide 会自动处理并和该 Activity 的生命周期绑定
            mImageLoader.loadImage(viewHolder.itemView.getContext(),
                    ImageConfigImpl
                            .builder()
                            .placeholder(R.drawable.ic_vector_net_error)
                            .url(path)
                            .imageView(viewHolder.ivSelectPic)
                            .build());
           /* if (mimeType == PictureMimeType.ofAudio()) {
                viewHolder.ivSelectPic.setImageResource(R.drawable.picture_audio );
            } else {

            }*/
            //itemView 的点击事件
            if (mItemClickListener != null) {
                viewHolder.itemView.setOnClickListener(v -> {
                    int adapterPosition = viewHolder.getAdapterPosition();
                    mItemClickListener.onItemClick(adapterPosition, v);
                });
            }
        }
    }

    protected OnItemClickListener mItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(int position, View v);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mItemClickListener = listener;
    }

    public void setOnDeletePicClickListener(OnDeletePicClickListener onDeletePicClickListener) {
        this.mOnDeletePicClickListener = onDeletePicClickListener;
    }
}
